import qs from 'qs'
import moment from 'moment'

let formatRegExp = /%[sdj%]/g

import Vue from 'vue';
import storage from '@/utils/storage'
//站点初始化
export function iniWeb() {
  let portalSettingsInfo = JSON.parse(storage.session.get('portalSettingsInfo'))
  let theme = portalSettingsInfo.themeColor || "blue";
  let iconUrl = portalSettingsInfo.favicon;
  Vue.prototype.$webTitle= portalSettingsInfo.webTitle || '企业采购';
  // addTheme(theme)
  changeFavicon(iconUrl);
  // customerServiceInitLT(portalSettingsInfo);
}

// 动态修改网站图标
function changeFavicon(link) {
  if(!link || link.length==0) return;
  let $favicon = document.querySelector('link[rel="icon"]');
  // link标签存在的情况
  if ($favicon !== null) {
    $favicon.href = link;
  } else {
    // link标签不存在的情况
    $favicon = document.createElement("link");
    $favicon.rel = "icon";
    $favicon.sizes = "32*32";
    $favicon.href = link;
    document.head.appendChild($favicon);
  }
}
export function list2tree (data, f_id, f_pid, f_name, style) {
  var d,
    o,
    t = {}
  for (var i in data) {
    d = data[i]
    if (t[d[f_id]] && t[d[f_id]].id) continue
    o = {id: d[f_id], pid: d[f_pid], data: d}
    for (var i in style) o[i] = style[i]
    if (f_name) o.text = d[f_name]
    if (d.children) {
      o.children = d.children
      delete d.children
    }
    if (o.pid) {
      if (!t[o.pid]) {
        t[o.pid] = {children: [o]}
      } else if (!t[o.pid].children) {
        t[o.pid].children = [o]
      } else {
        t[o.pid].children.push(o)
      }
    }
    if (t[o.id]) {
      o.children = o.children
        ? o.children.concat(t[o.id].children)
        : t[o.id].children
    }
    t[o.id] = o
  }
  var tree = []
  for (var i in t) {
    if (!t[i].data) {
      tree = tree.concat(t[i].children)
    } else if (!t[i].data[f_pid]) tree.push(t[i])
  }
  return tree
}
export function list2MenuTree(data, f_id, f_pid, f_name, style) {

  var d, o, t = {};
  for (var i in data) {
    d = data[i];
    if (t[d[f_id]] && t[d[f_id]].id)
      continue;
    o = {...d, id: d[f_id], pId: d[f_pid], data: d};
    for (var i in style)
      o[i] = style[i];
    if (f_name)
      o.text = d[f_name];
    if (d.children) {
      o.children = d.children;
      delete d.children;
    }
    if (o.pId)
      if (!t[o.pId])
        t[o.pId] = {children: [o]};
      else if (!t[o.pId].children)
        t[o.pId].children = [o];
      else
        t[o.pId].children.push(o);
    if (t[o.id])
      o.children = o.children ? o.children.concat(t[o.id].children) : t[o.id].children;
    t[o.id] = o;
  }
  var tree = [];
  for (var i in t)
    if (!t[i].data)
      tree = tree.concat(t[i].children);
    else if (!t[i].data[f_pid])
      tree.push(t[i]);
  return tree;
}
export function list2treePerm(data, f_id, f_pid, f_name, style) {

  var d, o, t = {};
  for (var i in data) {
    d = data[i];
    if (t[d[f_id]] && t[d[f_id]].id)
      continue;
    o = {...d, id: d[f_id], pid: d[f_pid], data: d};
    for (var i in style)
      o[i] = style[i];
    if (f_name)
      o.text = d[f_name];
    if (d.children) {
      o.children = d.children;
      delete d.children;
    }
    if (o.pid)
      if (!t[o.pid])
        t[o.pid] = {children: [o]};
      else if (!t[o.pid].children)
        t[o.pid].children = [o];
      else
        t[o.pid].children.push(o);
    if (t[o.id])
      o.children = o.children ? o.children.concat(t[o.id].children) : t[o.id].children;
    t[o.id] = o;
  }
  var tree = [];
  for (var i in t)
    if (!t[i].data)
      tree = tree.concat(t[i].children);
    else if (!t[i].data[f_pid])
      tree.push(t[i]);
  return tree;
}
// 功能
// 深拷贝
export const deepclone = obj => {
  var o
  // 如果  他是对象object的话  , 因为null,object,array  也是'object';
  if (typeof obj === 'object') {
    // 如果  他是空的话
    if (obj === null) {
      o = null
    } else {
      // 如果  他是数组arr的话
      if (obj instanceof Array) {
        o = []
        for (var i = 0, len = obj.length; i < len; i++) {
          o.push(deepclone(obj[i]))
        }
        // 如果  他是对象object的话
      } else {
        o = {}
        for (var j in obj) {
          o[j] = deepclone(obj[j])
        }
      }
    }
  } else {
    o = obj
  }
  return o
}

export function parseUrlToRoute (url) {
  if (url.indexOf('?') === -1) {
    return {path: url, query: {}}
  }
  let urlArr = url.split('?')
  let route = urlArr[0]
  let query = qs.parse(urlArr[1])
  Object.keys(query).forEach(item => {
    query[item] = Base64.encode(query[item])
  })
  return {path: route, query: query}
}
export function previewFile(fileUrl) {
  return fileUrl.endsWith('.png') || fileUrl.endsWith('.jpg') || fileUrl.endsWith('.jpeg') || fileUrl.endsWith('.gif') || fileUrl.endsWith('.ico') || fileUrl.endsWith('.svg');
}
/**
 * 判断是否为空
 * @param str
 * @returns {boolean}
 */
export function isEmpty (str) {
  if (
    !str ||
    str == null ||
    str === 'null' ||
    str === 'undefined' ||
    typeof str === 'undefined' ||
    str.length === 0 ||
    str === ''
  ) {
    return true
  }
  return false
}

export function format () {
  for (
    var _len = arguments.length, args = Array(_len), _key = 0;
    _key < _len;
    _key++
  ) {
    args[_key] = arguments[_key]
  }

  var i = 1
  var f = args[0]
  var len = args.length
  if (typeof f === 'function') {
    return f.apply(null, args.slice(1))
  }
  if (typeof f === 'string') {
    var str = String(f).replace(formatRegExp, function (x) {
      if (x === '%%') {
        return '%'
      }
      if (i >= len) {
        return x
      }
      switch (x) {
        case '%s':
          return String(args[i++])
        case '%d':
          return Number(args[i++])
        case '%j':
          try {
            return JSON.stringify(args[i++])
          } catch (_) {
            return '[Circular]'
          }
        default:
          return x
      }
    })
    return str
  }
  return f
}

/**
 * 乘法计算
 * @param arg1
 * @param arg2
 * @returns {number}
 * @constructor
 */
export function numberMul (arg1, arg2) {
  var m = 0
  var s1 = arg1.toString()
  var s2 = arg2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {
  }
  try {
    m += s2.split('.')[1].length
  } catch (e) {
  }

  return (
    (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) /
    Math.pow(10, m)
  )
}

/**
 *浮点型加法
 * @param arg1
 * @param arg2
 * @returns {string}
 * @constructor
 */
export function numberAdd (arg1, arg2) {
  var r1, r2, m, n
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  n = r1 >= r2 ? r1 : r2
  return ((arg1 * m + arg2 * m) / m).toFixed(n)
}

/**
 *浮点型减法
 * @param arg1
 * @param arg2
 * @returns {string}
 * @constructor
 */
export function numberSub (arg1, arg2) {
  var re1, re2, m, n
  try {
    re1 = arg1.toString().split('.')[1].length
  } catch (e) {
    re1 = 0
  }
  try {
    re2 = arg2.toString().split('.')[1].length
  } catch (e) {
    re2 = 0
  }
  m = Math.pow(10, Math.max(re1, re2))
  n = re1 >= re2 ? re1 : re2
  return ((arg1 * m - arg2 * m) / m).toFixed(n)
}

/**
 * 浮点型除法
 * @param arg1 除数
 * @param arg2 被除数
 * @param digit 保留的小数点后的位数
 * @returns {number}
 * @constructor
 */
export function numberDiv (arg1, arg2, digit) {
  var t1 = 0,
    t2 = 0,
    r1,
    r2
  try {
    t1 = arg1.toString().split('.')[1].length
  } catch (e) {
  }
  try {
    t2 = arg2.toString().split('.')[1].length
  } catch (e) {
  }
  r1 = Number(arg1.toString().replace('.', ''))
  r2 = Number(arg2.toString().replace('.', ''))
  // 获取小数点后的计算值
  var result = ((r1 / r2) * Math.pow(10, t2 - t1)).toString()

  var result2 = result.split('.')[1]
  if (isEmpty(result2)) {
    return Number(result.split('.')[0])
  }
  result2 = result2.substring(
    0,
    digit > result2.length ? result2.length : digit
  )

  return Number(result.split('.')[0] + '.' + result2)
}

/**
 * 保存到数据库的金额乘以100
 * @param arg1
 * @param arg2
 * @constructor
 */
export function moneyMul (arg1) {
  return numberMul(arg1, 100)
}

/**
 * 显示在页面上金额除以100
 * @param arg1
 * @param arg2
 * @constructor
 */
export function moneyDiv (arg1) {
  return numberDiv(arg1, 100, 2)
}

/**
 * 将后台返回的文本域内容中   \n 替换为浏览器识别的  <br>
 *
 */
export function replaceVal (val) {
  return val.replace(/\n/g, '<br>')
}

export function checkPassWord (length, value) {
  // 0： 表示第一个级别 1：表示第二个级别 2：表示第三个级别
  // 3： 表示第四个级别 4：表示第五个级别
  var modes = 0
  if (value.length < length) {//最初级别
    return modes
  }
  if (/\d/.test(value)) {//如果用户输入的密码 包含了数字
    modes++
  }
  if (/[a-z]/.test(value)) {//如果用户输入的密码 包含了小写的a到z
    modes++
  }
  if (/[A-Z]/.test(value)) {//如果用户输入的密码 包含了大写的A到Z
    modes++
  }
  if (/\W/.test(value)) {//如果是非数字 字母 下划线
    modes++
  }
  switch (modes) {
    case 1 :
      return 1
    case 2 :
      return 2
    case 3 :
      return 3
    case 4 :
      return 4
  }
}

export function makeFile (blob, filename) {
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename)
  } else {
    // for Non-IE (chrome, firefox etc.)
    let objectUrl = URL.createObjectURL(blob)
    let a = document.createElement('a')
    document.body.appendChild(a)
    a.setAttribute('style', 'display:none')
    a.setAttribute('href', objectUrl)
    a.setAttribute('download', filename)
    a.click()
    URL.revokeObjectURL(objectUrl)
    document.body.removeChild(a)
  }
}

export function dateFormatter (date) {
  return moment(new Date(date)).format('YYYY-MM-DD HH:mm:ss')
}

export function changeTimeStyle (time) {
  // 时间转换
  const json = new Date(time).toJSON()
  return new Date(+new Date(json) + 8 * 3600 * 1000)
    .toISOString()
    .replace(/T/g, ' ')
    .replace(/\.[\d]{3}Z/, '')
}

/**
 * changeURLParam 修改 URL 参数
 * @param url
 * @param name
 * @param value
 * @returns {string}
 */
export function changeURLParam (url, name, value) {
  if (typeof value === 'string') {
    value = value.toString().replace(/(^\s*)|(\s*$)/, '') // 移除首尾空格
  }
  let url2
  if (!value) { // remove
    let reg = eval('/(([\?|&])' + name + '=[^&]*)(&)?/i')
    let res = url.match(reg)
    if (res) {
      if (res[2] && res[2] === '?') { // before has ?
        if (res[3]) { // after has &
          url2 = url.replace(reg, '?')
        } else {
          url2 = url.replace(reg, '')
        }
      } else {
        url2 = url.replace(reg, '$3')
      }
    }
  } else {
    let reg = eval('/([\?|&]' + name + '=)[^&]*/i')
    if (url.match(reg)) { // edit
      url2 = url.replace(reg, '$1' + value)
    } else { // add
      let reg = /([?](\w+=?)?)[^&]*/i
      let res = url.match(reg)
      url2 = url
      if (res) {
        if (res[0] !== '?') {
          url2 += '&'
        }
      } else {
        url2 += '?'
      }
      url2 += name + '=' + value
    }
  }
  return url2
}

